package pzl.com.bluetooth.adapter;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import pzl.com.bluetooth.R;
import pzl.com.bluetooth.interfaces.IConnectService;

/**
 * @author zl.peng
 * @version [1.0, 2016-10-11]
 *          蓝牙设备列表适配器
 */
public class DeviceAdapter extends BaseAdapter {
    IConnectService mIConnectService;
    List<BluetoothDevice> deviceList;
    LayoutInflater layoutInflater;
    Context mContext;

    public DeviceAdapter(Context context) {
        mContext = context;
        deviceList = new ArrayList();
        layoutInflater = LayoutInflater.from(mContext);
    }


    @Override
    public int getCount() {
        return deviceList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        BluetoothDevice device = deviceList.get(position);
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.item_devicelist, null);
        }

        TextView tvDevice = (TextView) convertView.findViewById(R.id.tvDevice);
        if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
            tvDevice.setText(device.getName() + "[" + device.getAddress() + "]");
        } else {
            tvDevice.setText(device.getName() + "[" + device.getAddress() + "]" + " (已配对)");
            tvDevice.setTextColor(Color.parseColor("#91ff43"));
        }
        convertView.setOnClickListener(new OnItemClick(position));
        return convertView;
    }

    public void addDevice(BluetoothDevice client) {
        deviceList.add(client);
    }

    public void clearData() {
        deviceList.clear();
    }


    class OnItemClick implements View.OnClickListener {
        int mPosition;

        public OnItemClick(int position) {
            mPosition = position;
        }

        @Override
        public void onClick(View v) {
            if (mIConnectService != null)
                mIConnectService.onConnectService(deviceList.get(mPosition));
        }
    }

    public void registerIConnectService(IConnectService connectService) {
        mIConnectService = connectService;
    }

}
